package controllers

import models.User
import play.api.data.Forms._
import play.api.data._
import play.api.mvc.{Action, Controller}

/**
 * 用户controller
 * Created by zzb on 15/9/28.
 */
class UserController extends Controller {
  val userForm = Form(
    mapping(
      "id" -> number,
      "name" -> nonEmptyText(3),
      "password" -> nonEmptyText(6),
      "description" -> text
    )(User.apply)(User.unapply)
  )


  def list = Action { implicit request =>
    Ok(views.html.user.list(User.findAll))
  }

  def add = Action { implicit request =>
    Ok(views.html.user.add(userForm))
  }

  def addPost = Action { implicit request =>
    userForm.bindFromRequest().fold(
      hasErrors => {
        println (hasErrors)
        BadRequest
      },
      user => {
        User.create(user)
        Redirect(routes.UserController.list())
      }
    )
  }
}
